<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024"
    @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #organizationSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择组织" @search="openOrganization" />
      </template>
    </BasicForm>
    <a-button :disabled="isDetail" @click="searchFormOpen">筛选条件
      <Icon icon="mdi:search"></Icon>
    </a-button>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="排产订单" key="psProductionPlanMpsItem" :forceRender="true">
        <JVxeTable keep-source resizable ref="psProductionPlanMpsItem"
          :loading="psProductionPlanMpsItemTable.loading"
          :columns="psProductionPlanMpsItemTable.columns"
          :dataSource="psProductionPlanMpsItemTable.dataSource" :height="340"
          :disabled="formDisabled" :toolbar="true" rowSelection
          :toolbarConfig="toolbarConfig" />
      </a-tab-pane>
    </a-tabs>
    <searchModal @register="searchFormModal" @getSelectResult="searchFormSuccess"></searchModal>
    <organizationSelectModel @register="organizationRegModal" @getSelectResult="organizationHandleSuccess" v-bind="getBindValue" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import {
    ref,
    computed,
    unref,
    reactive
  } from 'vue';
  import {
    BasicModal,
    useModalInner,
    useModal
  } from '/@/components/Modal';
  import {
    BasicForm,
    useForm
  } from '/@/components/Form/index';
  import {
    useJvxeMethod
  } from '/@/hooks/system/useJvxeMethods.ts'
  import {
    formSchema,
    psProductionPlanMpsItemColumns
  } from '../PsProductionPlanMps.data';
  import {
    saveOrUpdate,
    psProductionPlanMpsItemList
  } from '../PsProductionPlanMps.api';
  import {
    VALIDATE_FAILED
  } from '/@/utils/common/vxeUtils';
  import organizationSelectModel from '/@/views/supplier/purchaseManager/busBuyingRequisition/components/organizationSelectModel.vue';
  import searchModal from './searchModal.vue';
  import { useDeptStore } from '/@/store/modules/dept';
  const deptStore = useDeptStore();
  
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const isDetail = ref<boolean>(false)
  const formDisabled = ref(false);
  const refKeys = ref(['psProductionPlanMpsItem', ]);
  const activeKey = ref('psProductionPlanMpsItem');
  const psProductionPlanMpsItem = ref();
  const tableRefs = {
    psProductionPlanMpsItem,
  };
  const [organizationRegModal, { openModal: openOrganizationModal }] = useModal();
  // 工具栏的按钮配置
  const toolbarConfig = reactive({
    // add 新增按钮；remove 删除按钮；clearSelection 清空选择按钮
    btn: [ 'remove', 'clearSelection'],
    // btn: [],
  });
  const psProductionPlanMpsItemTable = reactive({
    loading: false,
    dataSource: [],
    columns: psProductionPlanMpsItemColumns
  })
  //表单配置
  const [registerForm, {
    setProps,
    resetFields,
    setFieldsValue,
    validate
  }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: {
      span: 8
    }
  });
  //表单赋值
  const [registerModal, {
    setModalProps,
    closeModal
  }] = useModalInner(async (data) => {
    //重置表单
    await reset();
    setModalProps({
      confirmLoading: false,
      showCancelBtn: data?.showFooter,
      showOkBtn: data?.showFooter
    });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !!data?.isDetail
    formDisabled.value = !data?.showFooter;
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
      requestSubTableData(psProductionPlanMpsItemList, {
        id: data?.record?.id
      }, psProductionPlanMpsItemTable)
    }
    // 隐藏底部时禁用整个表单
    setProps({
      disabled: !data?.showFooter
    })
  });
  //方法配置
  const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
    requestAddOrEdit, classifyIntoFormData, tableRefs, activeKey, refKeys);

  //设置标题
  const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));

  // 注册筛选模态框
  const [searchFormModal, {
    openModal: openSearchFormModal
  }] = useModal();

  async function reset() {
    await resetFields();
    activeKey.value = 'psProductionPlanMpsItem';
    psProductionPlanMpsItemTable.dataSource = [];
  }

  function classifyIntoFormData(allValues) {
    let main = Object.assign({}, allValues.formValue)
    return {
      ...main, // 展开
      psProductionPlanMpsItemList: allValues.tablesValue[0].tableData,
    }
  }

  //打开选择组织
  function openOrganization() {
    openOrganizationModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  //组织回写
  function organizationHandleSuccess(val) {
    setFieldsValue({
      planOrganizationName: val[0].label,
      planOrganizationId: val[0].value,
    });
  }
  // 打开筛选模态框
  function searchFormOpen() {
    openSearchFormModal(true, {
      isUpdate: false,
      showFooter: false
    })
  }
  // 筛选模态框回写数据
  function searchFormSuccess(val) {
    let tempArr = [];
    val.map(item => {
      item.orderRowNum = item.rowNum;
      item.productQuantity = item.ableProductQuantity;
      item.orderCenterId = item.id;
      tempArr.push(item); 
    })
    
    psProductionPlanMpsItemTable.dataSource = tempArr;
  }
  //表单提交事件
  async function requestAddOrEdit(values) {
    values.psProductionPlanMpsItemList.map(item => {
      delete item.id;
    })
    try {
      setModalProps({
        confirmLoading: true
      });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({
        confirmLoading: false
      });
    }
  }

</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%
  }

  :deep(.ant-calendar-picker) {
    width: 100%
  }

</style>
